package cn.picclife.mwx.manager.util.filter;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import cn.picclife.mwx.manager.util.FtpFileUtil;
import cn.picclife.mwx.manager.util.LogUtil;
import cn.picclife.mwx.manager.util.ThreadLocalContext;
import cn.picclife.mwx.manager.util.uniqueseq.UniqueSeq;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 处理跨域问题
 * @author 59238
 *
 */
public class LoggerFilter implements Filter{
	private static final Log log = LogFactory.getLog(LoggerFilter.class);
	@Override
	public void destroy() {
		
	}


	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// 请求开始时间
		long startTime = System.currentTimeMillis();
		
		try {
			initThreadLocal(req);
			chain.doFilter(req, res);
		} catch (Exception e) {
			log.error("异常信息"+e.getMessage(),e);
		}finally{
			LogUtil.debug("调用结束,本次请求用时：" + (System.currentTimeMillis() - startTime) / 1000.0000 
					+ "秒 thread:[" + ThreadLocalContext.get().getThreadUUID() 
					+ "] ip:[" + ThreadLocalContext.get().getIp()
					+ "] project:[" + ThreadLocalContext.get().getProject()
					+ "] function:[" + ThreadLocalContext.get().getFunction()
					+ "]");
		}
	}


	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	/**
	 * 初始化ThreadLocalContext
	 */
	private void initThreadLocal(ServletRequest request){
		// 线程标识
		ThreadLocalContext.get().setThreadUUID(UniqueSeq.shortUUID());
		// 请求IP
		ThreadLocalContext.get().setIp(getIpAddress((HttpServletRequest) request));
		// 请求项目
		ThreadLocalContext.get().setProject(((HttpServletRequest) request).getContextPath().replace("/", ""));
		// 请求接口
		ThreadLocalContext.get().setFunction(getFunction((HttpServletRequest) request));
	}

    /** 
      * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, 
      * @param request 
      * @return 
      */  
     private String getIpAddress(HttpServletRequest request) {  
         String ip = request.getHeader("x-forwarded-for");  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
             ip = request.getHeader("Proxy-Client-IP");  
         }  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
             ip = request.getHeader("WL-Proxy-Client-IP");  
         }  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
             ip = request.getHeader("HTTP_CLIENT_IP");  
         }  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
             ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
         }  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
             ip = request.getRemoteAddr();  
         }  
         return ip;  
     }
	
     /** 
      * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, 
      * @param request 
      * @return 
      */  
     public static String getFunction(HttpServletRequest request) {
         String uri = request.getRequestURI();// 返回请求行中的资源名称
         // String url = request.getRequestURL().toString();// 获得客户端发送请求的完整url
         // String ip = request.getRemoteAddr();// 返回发出请求的IP地址
         // String params = request.getQueryString();// 返回请求行中的参数部分
         // String host = request.getRemoteHost();// 返回发出请求的客户机的主机名
         // int port = request.getRemotePort();// 返回发出请求的客户机的端口号。
         String[] split = uri.split("/");
         return split[2];
     }
     
}
